import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'
import Home from '../views/home.vue'
import About from '../views/about.vue'
import Doc from '../views/doc.vue'
import AdminEbook from '../views/admin/admin-ebook.vue'
import AdminCategory from '../views/admin/admin-category.vue'
import AdminDoc from '../views/admin/admin-doc.vue'
import AdminUser from '../views/admin/admin-user.vue'
import store from "@/store";
import {Tool} from "@/util/tool";

const routes: Array<RouteRecordRaw> = [
  {
    path: '/',
    name: 'Home',
    component: Home
  },
  {
    path: '/about',
    name: 'About',
    component: About
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.  本项目比较小，所以就不用懒加载组件了，编译时就一起加载进来
//     component: () => import(/* webpackChunkName: "about" */ '../views/about.vue')
  },
  {
      path: '/admin/user',
      name: 'AdminUser',
      component: AdminUser,
      // meta是元数据，即自定义信息，比如我们针对需要登录的路由，配置一个loginRequire为true的属性
      meta: {
        loginRequire: true
      }
    },
  {
      path: '/admin/ebook',
      name: 'AdminEbook',
      component: AdminEbook,
      meta: {
        loginRequire: true
      }
    },
  {
      path: '/admin/category',
      name: 'AdminCategory',
      component: AdminCategory,
      meta: {
        loginRequire: true
      }
    },
  {
      path: '/admin/doc',
      name: 'AdminDoc',
      component: AdminDoc,
      meta: {
        loginRequire: true
      }
    },
  {
      path: '/doc',
      name: 'Doc',
      component: Doc
    }
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})

// 路由拦截登录（需要登录的路由，若没有登录token，则重定向到首页）【这段逻辑在vue2和vue3中均支持】
// 参数，to--新路由，from--旧路由，next是它的一个方法
router.beforeEach((to, from, next) => {
    // 对meta.loginRequire属性做监控拦截
    if(to.matched.some(function (item) {
        console.log(item, "是否需要登录校验：", item.meta.loginRequire) ;    // 这个的item就是目标路由to的整个信息
        return item.meta.loginRequire
    })){
        const loginUser = store.state.user;
        if(Tool.isEmpty(loginUser)){
            console.log("用户未登录！");
            next('/') ;                     // 路由到首页
        } else {
            next() ;    // 跳到目标路由to，即不拦截
        }
    } else {
        next() ; // 跳到目标路由to，即不拦截
    }
});

export default router
